package test.demo.Exception;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import test.demo.Error.ErrorVO;
import test.demo.Result.GlobalResult;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public String exceptionHandler(BindException e, HttpServletRequest request) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String failMsg = Objects.requireNonNull(fieldError).getDefaultMessage();

        System.out.println("URL:"+request.getRequestURI()+ "绑定异常: "+failMsg);
        return "URL:"+request.getRequestURI()+ "绑定异常: "+failMsg;
    }

//    @ExceptionHandler(java.sql.SQLException.class)
//    public String exceptionHandler2(SQLException e, HttpServletRequest request) {
//
//
//        System.out.println("URL:"+request.getRequestURI()+ "数据库异常: "+e.getErrorCode());
//        return "URL:"+request.getRequestURI()+ "数据库异常: "+e.getErrorCode();
//    }

//    @ExceptionHandler(BaseException.class)
//    public GlobalResult exceptionHandler2(BaseException e, HttpServletRequest request){
//        ErrorVO errorVO = new ErrorVO(e, request.getRequestURI());
//        return GlobalResult.error(errorVO);
//    }
//
//    @ExceptionHandler({Exception.class})
//    public GlobalResult exceptionHandler3(Exception e, HttpServletRequest request){
//        ErrorVO errorVO = new ErrorVO(SQLException.REPEAT_OF_USER_NAME,request.getRequestURI());
////        System.out.println(errorVO);
//        return GlobalResult.error(errorVO);
//    }
//
//    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
//    public GlobalResult exceptionHandler3(HttpRequestMethodNotSupportedException e,HttpServletRequest request){
//        ErrorVO errorVO = new ErrorVO(e,request.getRequestURI());
//        return GlobalResult.error(errorVO);
//    }
}
